package datastruct.uf;

/**
 * @author RunningShrimp
 * @date 2021/5/28  17:55
 * @see <a href=""></a>
 */
public class QuickUnionFindByCompress2 implements UnionFind {
    private final int[] parent;

    private final int[] ranks;

    public QuickUnionFindByCompress2(int size) {
        parent = new int[size];
        ranks = new int[size];
        for (int i = 0; i < parent.length; i++) {
            parent[i] = i;
            ranks[i] = 1;
        }

    }

    @Override
    public int getSize() {
        return parent.length;
    }

    private int find(int p) {
        if (p < 0 || p > parent.length) {
            throw new IndexOutOfBoundsException("索引无效");
        }
        if (p != parent[p]) {
            parent[p] = find(parent[p]);
        }
        return parent[p];
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }
        //根据两个元素所在树的rank不同判断合并方向
        //将rank低的集合合并到rank高的集合上
        if (ranks[pRoot] < ranks[qRoot]) {
            parent[pRoot] = qRoot;
        } else if (ranks[pRoot] > ranks[qRoot]) {
            parent[qRoot] = pRoot;
        } else {
            parent[qRoot] = pRoot;
            ranks[pRoot] += 1;
        }
    }
}
